package com.nefu.softlab.xjwc.shiro;

import com.nefu.softlab.xjwc.config.MyByteSource;
import com.nefu.softlab.xjwc.mapper.UserMapper;
import com.nefu.softlab.xjwc.model.Access;
import com.nefu.softlab.xjwc.model.Role;
import com.nefu.softlab.xjwc.model.User;
import org.apache.commons.collections.CollectionUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

/**
 * @author : Ar1es
 * @date : 2020/1/12
 * @since : Java 8
 */
public class CustomRealm extends AuthorizingRealm {

    @Autowired
    private UserMapper userMapper;

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        //获取用户
        User user = (User) SecurityUtils.getSubject().getPrincipal();
        List<String> list = new ArrayList<>();
        List<String> roleNameList = new ArrayList<>();
        Set<Role> roles = user.getRoles();
        if(CollectionUtils.isNotEmpty(roles)){
            for (Role role:
                    roles) {
                roleNameList.add(role.getRoleName());
                Set<Access> accessSet = role.getAccesses();
                if(CollectionUtils.isNotEmpty(accessSet)) {
                    for (Access access :
                            accessSet) {
                        list.add(access.getName());
                    }
                }
            }
        }
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        info.addStringPermissions(list);
        info.addRoles(roleNameList);

        return info;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        //认证用户 token
        UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;

        String phone = token.getUsername();

        User user = userMapper.selectByPhone(phone);

        System.out.println("当前认证用户name : " + phone);
        if (null == user) {
            throw new UnknownAccountException("该用户名不存在");
        } else {
            //当前认证用户name
            String realmName = getName();

            SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(user, user.getPassword(), new MyByteSource(user.getPhone()), realmName);

            return info;
        }
    }

    @Override
    public void clearCache(PrincipalCollection principals) {
        super.clearCache(principals);
    }




}
